package org.pku_uestc.hackathon.sensor.mobile;

import org.pku_uestc.hackathon.SilentActivity.WhiteListInterface;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;

public class SmsReceiver extends BroadcastReceiver {

	public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

	private WhiteListInterface whitelist;
	
	private String[] phones;
	
	public void setPhones(String[] phones, WhiteListInterface whitelist) {
		this.phones = phones;
		this.whitelist = whitelist;
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		
		if (intent.getAction().equals(SMS_RECEIVED))
		{
			int length = phones.length;
			String phone = null;
			SmsMessage[] messages = getMessagesFromIntent(intent);
			for (SmsMessage message : messages) {
				phone = message.getOriginatingAddress();
			}
			for (int i = 0; i < length; i++) {
				if(phones[i].equals(phone)) {
					whitelist.onPass(WhiteListInterface.TYPE_SMS);
					break;
				}
			}
		}
	}

	public final SmsMessage[] getMessagesFromIntent(Intent intent) {
		Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
		byte[][] pduObjs = new byte[messages.length][];
		for (int i = 0; i < messages.length; i++) {
			pduObjs[i] = (byte[]) messages[i];
		}
		byte[][] pdus = new byte[pduObjs.length][];
		int pduCount = pdus.length;
		SmsMessage[] msgs = new SmsMessage[pduCount];
		for (int i = 0; i < pduCount; i++) {
			pdus[i] = pduObjs[i];
			msgs[i] = SmsMessage.createFromPdu(pdus[i]);
		}
		return msgs;
	}

}
